package com.hopu.blb_erp.controller;

import com.hopu.blb_erp.entity.PageEntity;
import com.hopu.blb_erp.entity.User;
import com.hopu.blb_erp.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api
@RestController
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @ApiOperation("根据用户名查询用户")
    @GetMapping("/user")
    public ResponseEntity<User> findUser(){
        //从SpringSecurity取得登录的用户名
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user1 = userService.findByName(user.getUsername());
        if(user1 != null){
            return ResponseEntity.ok(user1);
        }else {
            return null;
        }
    }

    @ApiOperation("查询所有用户")
    @GetMapping("/users")
    public ResponseEntity<List<User>> findAll(){
        List<User> user = userService.find();
        return ResponseEntity.ok(user);
    }

    @ApiOperation("分页查询用户")
    @GetMapping("/users/{current}/{pageSize}")
    public ResponseEntity<PageEntity> findPage(@PathVariable("current")Integer current, @PathVariable("pageSize")Integer pageSize){
        // 查询角色总数
        Integer count = userService.findCount();
        // 分页查询订单
        List<User> users = userService.findPage((current-1) * pageSize, pageSize);
        // 包装到分页对象
        PageEntity<User> page = new PageEntity<>();
        page.setCount(count);
        page.setData(users);
        return ResponseEntity.ok(page);
    }

    @ApiOperation("添加用户")
    @PostMapping("/user")
    public ResponseEntity<String> add(@RequestBody User user){
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userService.save(user);
        return ResponseEntity.ok("ok");
    }


    @ApiOperation("删除用户")
    @DeleteMapping("/user/{id}")
    public ResponseEntity<String> delete(@PathVariable("id") Integer id){
        userService.removeById(id);
        return ResponseEntity.ok("ok");
    }

    @ApiOperation("修改用户状态")
    @PutMapping("/user/{id}")
    public ResponseEntity<String> update(@PathVariable("id") Integer id){
        User user = new User();
        user.setId(id);
        userService.modify(user);
        return ResponseEntity.ok("ok");
    }
}
